package com.qf.push.service.impl;

import com.qf.push.dao.IdemDao;
import com.qf.push.dao.MessageDao;
import com.qf.push.model.Idem;
import com.qf.push.model.IdemExample;
import com.qf.push.model.Message;
import com.qf.push.service.PushService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 30909
 *
 */
@Service
public class PushServiceImpl implements PushService {

    @Resource
    private MessageDao messageDao;

    @Resource
    private IdemDao idemDao;

    /**
     * 只要出现异常就回滚
     * @param message
     * @param requestId
     * @return
     */
    @Transactional(rollbackFor =  Exception.class)
    @Override
    public int saveMessage(Message message,long requestId) {

        messageDao.insertSelective(message);
        Idem idem = new Idem();
        idem.setTime(System.currentTimeMillis());
        idem.setRequestid(requestId);

        return idemDao.insertSelective(idem);
    }

    /**
     * 查询request 是否存在
     *
     * @param requestId 保证幂等性的请求id
     * @return 此 id 是否保存该
     */
    @Override
    public boolean isIdem(Long requestId) {
        IdemExample idemExample = new IdemExample();
        IdemExample.Criteria criteria = idemExample.createCriteria();
        criteria.andRequestidEqualTo(requestId);


        List<Idem> idems = idemDao.selectByExample(idemExample);
        if (idems != null&& idems.size()>0) {
            //存在
            return true;
        }
        //不存在
        return false;
    }
}
